﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using web.core.ViewModels;
using web.core.Models;
using web.component;
using System.IO; 

namespace web.core.Controllers
{
    public class admTranslateController : baseController
    {

        //constructor
        #region inner function
        public List<TranslateGroupViewModels> CreateGroupList()
        {
            var lst = new List<TranslateGroupViewModels> { 
                createItemGroup(global_const.E_TRANS_GROUP.PAGE_LAYOUT, "Page layout"),
                createItemGroup(global_const.E_TRANS_GROUP.COMMON, "Dùng chung"),
                createItemGroup(global_const.E_TRANS_GROUP.COMMON_FORM, "Dùng chung Form"), 
                createItemGroup(global_const.E_TRANS_GROUP.PRODUCT, "Sản phẩm"),
                createItemGroup(global_const.E_TRANS_GROUP.ARTICLE, "Tin tức - bài viết")
            };
            return lst;
        }
        private TranslateGroupViewModels createItemGroup(global_const.E_TRANS_GROUP gid, string gname) {
            var it = new TranslateGroupViewModels() {
                group_id = (int)gid,
                group_name = gname
            };
            return it;
        }
        #endregion

        //------------------------------------
        //trans_list
        //------------------------------------
        #region trans_list PAGE
        public ActionResult trans_list()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult get_list(int? pageindex, int? groupId)
        {
            return get_list(pageindex, admin_const.PAGE_LIST_SIZE, groupId ?? (int)global_const.E_TRANS_GROUP.COMMON);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult get_list(int? pageindex, int? pagesize, int? groupId)
        { 
            var page_view = new ViewModels.TranslatePageListViewModels()
            { 
                //list_group = accountModels.getListUserGroup(),
                list_pagesize = GetSizePagingPublic(pagesize ?? admin_const.PAGE_LIST_SIZE),
                pagesize = pagesize ?? admin_const.PAGE_LIST_SIZE
            };
            TryUpdateModel(page_view);

            //admin_const.DEFAULT_LANGUAGE_ID

            var lst_gr = CreateGroupList();
            int gid = groupId ?? (int)global_const.E_TRANS_GROUP.COMMON;
            page_view.select_list_trans_group = new SelectList(lst_gr, "group_id", "group_name");
            page_view.groupId = gid;
            
            page_view.page_list_translate = Models.transModels.translate_plist(pageindex ?? 1,
                                                                                pagesize ?? admin_const.PAGE_LIST_SIZE,
                                                                                admin_const.DEFAULT_LANGUAGE_ID, gid);

            //----save to xml
            var save_xml = Request.Form["save_xml"];
            var save_xml_all = Request.Form["save_xml_all"];
            if (!string.IsNullOrEmpty(save_xml) || !string.IsNullOrEmpty(save_xml_all))
            {
                //noi luu tru file
                var sfolder = siteSettingModels.getValueByID(global_const.STORAGE_CONFIG, admin_const.NO_LANGUAGE);
                try
                {                    
                    if (!string.IsNullOrEmpty(sfolder))
                    {
                        string strResult = "";
                        // tao theo nhom
                        if (!string.IsNullOrEmpty(save_xml))
                        {
                            strResult = createXml(sfolder, gid);
                            if (strResult == "Y")
                                ViewBag.result_message = admin_const.UPDATE_OK;
                            else
                                ViewBag.result_message = strResult;
                        }
                        else {
                            //tao tat ca cac nhom
                            foreach (var gitem in lst_gr)
                            {
                                strResult = createXml(sfolder, gitem.group_id);
                                if (strResult == "Y")
                                    ViewBag.result_message = admin_const.UPDATE_OK;
                                else
                                    ViewBag.result_message += strResult;
                            }
                        }
                    }
                    else
                    {
                        ViewBag.result_message = "Chưa thiết lập nơi lưu file config";
                    }
                }
                catch (Exception ex)
                {
                    ViewBag.result_message += "<br>" + ex.ToString();
                }
                if (ViewBag.result_message != null)
                    ViewBag.result = true;

            }
            return PartialView("../Shared/translate/list_trans", page_view);
        }

        //tao file theo nhom
        private string createXml(string sfolder, int groupid)
        {
            try
            {
                sfolder += Path.DirectorySeparatorChar + global_const.STORAGE_FOLDER + Path.DirectorySeparatorChar;
                var lstLang = languageModels.get_list_language();
                foreach (var lang in lstLang)
                {
                    string cf_file = sfolder + string.Format(global_const.TRANS_XML_FILE, lang.language_code, groupid);
                    var dic = transModels.get_list_trans(groupid, lang.language_id);
                    Uxmlhelper.CreateTranslateFile(dic, lang.language_code, cf_file);
                }
                return "Y";
            }
            catch (Exception ex) {
                return "<br>" + ex.ToString();
            }
        }
        #endregion

        //------------------------------------
        //trans_edit
        //------------------------------------
        #region trans_edit PAGE
        public ActionResult trans_edit()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult ctr_trans_edit(string id, int? gid)
        {
            var itemid = id;
            int group_id = gid ?? (int)global_const.E_TRANS_GROUP.COMMON;
            if (string.IsNullOrEmpty(id))
                ViewBag.isAdd = true;
            else
                ViewBag.isAdd = false;

            ViewModels.TranslateViewModels item_view;
            //var item_view = new ViewModels.LanguageViewModels();
            var lstit = transModels.ListByLbl(itemid, group_id);
            var lstlanguage = languageModels.get_list_language();
            var list_items = new List<data.entities.translate>();
            var lstGroup = CreateGroupList();

            if (lstit.Count > 0)
            {   
                foreach (var it in lstlanguage)
                {
                    var sitem = transModels.getByID(itemid, group_id, it.language_id);
                    sitem.language_id = it.language_id;
                    // sitem.setting_type = Convert.ToInt16(type);
                    list_items.Add(sitem);
                }               
                //item_view = new TranslateViewModels()
                //{
                //    trans_label = itemid,
                //    trans_group = group_id,
                //    select_list_trans_group = new SelectList(lstGroup, "group_id", "group_name"),
                //    listLanguage = lstlanguage,
                //    listItems = list_items
                //};
            }
            else {
                foreach (var it in lstlanguage)
                {
                    list_items.Add(new data.entities.translate()
                    {
                        language_id = it.language_id
                    });
                }
            }
            item_view = new TranslateViewModels()
            {
                trans_label = itemid,
                trans_group = group_id,
                select_list_trans_group = new SelectList(lstGroup, "group_id", "group_name"),
                listLanguage = lstlanguage,
                listItems = list_items
            };
            //var lst_lang = languageModels.get_list_language();
            //item_view.select_list_language = new SelectList(lst_lang, "language_id", "language_desc", item_view.language_id);
            //item_view.select_list_status = new List<SelectListItem>() {  
            //        new SelectListItem{Selected=item_view.show == true?true:false, Text = "Kích hoạt", Value = "true" },
            //        new SelectListItem{Selected=item_view.show == false?true:false, Text = "Vô hiệu hóa", Value = "false" }
            //};

            return PartialView("../Shared/translate/edit_trans", item_view);
        }

        [ChildActionOnly]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult ctr_trans_edit(FormCollection collection)
        {
            var item_view = new ViewModels.TranslateViewModels();
            TryUpdateModel(item_view);

            if (string.IsNullOrEmpty(item_view.trans_label))
            {
                ViewBag.result_message = "Key không để trống.";
                ViewBag.result = false;
                return PartialView("../Shared/translate/edit_trans", item_view);
            }
            //update
            for (int i = 0; i < item_view.listItems.Count; i++)
            {
                var itm = item_view.listItems[i];
                
                    itm.trans_label = item_view.trans_label;
                    itm.trans_group = item_view.trans_group;

                    transModels.trans_update(itm);
            } 

            //foreach(var it in item_view.listItems)
            //      siteSettingModels.adm_setting_update(it);

            ViewBag.result_message = admin_const.UPDATE_OK;
            ViewBag.redirect = "/vi/admTranslate/trans_list";
            return PartialView("../Shared/control_redirect");
        }
        #endregion
    }
}